package com.lry.aspect;

import com.lry.anno.ExceptionListener;
import com.lry.handler.ExceptionHandler;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;

import java.util.Arrays;

@Aspect
@Slf4j
public class ExceptionNoticeAspect {

    private ExceptionHandler exceptionHandler;

    public ExceptionNoticeAspect(ExceptionHandler exceptionHandler){
        this.exceptionHandler = exceptionHandler;
    }

    @AfterThrowing(value = "@within(listener)",throwing = "e",argNames ="listener,e")
    public void exceptionNotice(JoinPoint joinPoint, ExceptionListener listener,RuntimeException e){
        handlerExceptionNotice(e,joinPoint.getSignature().getName(),joinPoint.getArgs());
    }

    @AfterThrowing(value = "@annotation(listener)", throwing = "e", argNames = "listener,e")
    public void exceptionNoticeWithMethod(JoinPoint joinPoint, ExceptionListener listener, RuntimeException e) {
        handlerExceptionNotice(e, joinPoint.getSignature().getName(), joinPoint.getArgs());
    }

    private void handlerExceptionNotice(RuntimeException e,String methodName,Object[]args){
        log.debug("出现异常：" + methodName
                + String.join(",", Arrays.stream(args).map(x -> x.toString()).toArray(String[]::new)));
        exceptionHandler.createNotice(e, methodName, args);
    }

}
